#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;
int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
/*
void *getTicket(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    const char *name = td->_threadName.c_str();
    while (true)
    {
        {
            LockGuard lg(&mutex); // 临时的LockGuard对象  RAII风格的锁
            if (tickets > 0)
            {
                usleep(1000);
                --tickets;
                printf("%s抢了1张票，还剩%d张票\n", name, tickets);
            }
            else
            {

                break;
            }
        }
        usleep(10);
    }

    printf("票已售空!\n");
    return nullptr;
}
*/

void *Count(void *args)
{
    uint64_t number = *(uint64_t *)args;
    cout << "pthread:" << number << " create successfully." << endl;
    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        cout << "pthread " << number << " , cnt:" << cnt++ << endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    for (uint64_t i = 0; i < 5; ++i)
    {
        int *no = new int(i);
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void *)no);
        usleep(100);
    }
    sleep(3);
    cout << "main thread ctrl begin:" << endl;
    while (true)
    {
        sleep(1);
        cout << "signal one thread:" << endl;
        pthread_cond_signal(&cond);
    }

    return 0;
}